"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDefaultAccountOverrideFilePath = exports.getDefaultAccountOverrideAccountId = void 0;
const findup_sync_1 = __importDefault(require("findup-sync"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = require("../lib/path");
const config_1 = require("../constants/config");
const lang_1 = require("../utils/lang");
const FileSystemError_1 = require("../models/FileSystemError");
const index_1 = require("./index");
const i18nKey = 'config.defaultAccountOverride';
function getDefaultAccountOverrideAccountId() {
    const defaultAccountOverrideFilePath = getDefaultAccountOverrideFilePath();
    if (!defaultAccountOverrideFilePath) {
        return null;
    }
    let source;
    try {
        source = fs_extra_1.default.readFileSync(defaultAccountOverrideFilePath, 'utf8');
    }
    catch (e) {
        throw new FileSystemError_1.FileSystemError({ cause: e }, {
            filepath: defaultAccountOverrideFilePath,
            operation: 'read',
        });
    }
    const accountId = parseInt(source);
    if (isNaN(accountId)) {
        throw new Error((0, lang_1.i18n)(`${i18nKey}.getDefaultAccountOverrideAccountId.errorHeader`, {
            hsAccountFile: defaultAccountOverrideFilePath,
        }), {
            // TODO: This is improper use of cause, we should create a custom error class
            cause: config_1.DEFAULT_ACCOUNT_OVERRIDE_ERROR_INVALID_ID,
        });
    }
    const accounts = (0, index_1.getAllConfigAccounts)();
    const account = accounts?.find(account => account.accountId === accountId);
    if (!account) {
        throw new Error((0, lang_1.i18n)(`${i18nKey}.getDefaultAccountOverrideAccountId.errorHeader`, {
            hsAccountFile: defaultAccountOverrideFilePath,
        }), {
            // TODO: This is improper use of cause, we should create a custom error class
            cause: config_1.DEFAULT_ACCOUNT_OVERRIDE_ERROR_ACCOUNT_NOT_FOUND,
        });
    }
    return account.accountId;
}
exports.getDefaultAccountOverrideAccountId = getDefaultAccountOverrideAccountId;
function getDefaultAccountOverrideFilePath() {
    return (0, findup_sync_1.default)([config_1.DEFAULT_ACCOUNT_OVERRIDE_FILE_NAME], {
        cwd: (0, path_1.getCwd)(),
    });
}
exports.getDefaultAccountOverrideFilePath = getDefaultAccountOverrideFilePath;
